#include "Thread.h"
#include <Windows.h>
#include <process.h>

#include "../Invoker/InvocationList.h"

namespace xgu{

Thread::TID Thread::getTid()
{
	return static_cast<TID>(::GetCurrentThreadId());
}

Thread::TLS Thread::TlsAlloc()
{
	return static_cast<TLS>(::TlsAlloc());
}

bool Thread::TlsFree( TLS tls )
{
	return ::TlsFree(static_cast<DWORD>(tls)) == TRUE;
}

bool Thread::TlsSet( TLS tls, void* value )
{
	return ::TlsSetValue(static_cast<DWORD>(tls), value) == TRUE;
}

void* Thread::TlsGet( TLS tls )
{
	return ::TlsGetValue(static_cast<DWORD>(tls));
}

void Thread::Start()
{
	_beginthread(ThreadEntry, 0, this);
}

Thread::Thread( const ThreadStart& thread_start )
{
	thread_start_ = new ThreadStart(thread_start);
}

void Thread::ThreadEntry( void* param )
{
	assert(param != NULL);
	Thread* thread = reinterpret_cast<Thread*>(param);
	(*(thread->thread_start_))();
	delete thread->thread_start_;
	thread->thread_start_ = NULL;
	
	_endthread();
}

}
